package vnetlab.ui.editor;

import java.awt.event.ComponentEvent;
import java.awt.event.ContainerEvent;
import java.awt.event.HierarchyEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.event.AncestorEvent;
import vnetlab.manager.Status;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JToolBar;
import javax.swing.TransferHandler;

import vnetlab.ui.editor.EditorActions.HistoryAction;
import vnetlab.ui.editor.EditorActions.NewAction;
import vnetlab.ui.editor.EditorActions.OpenAction;
import vnetlab.ui.editor.EditorActions.PrintAction;
import vnetlab.ui.editor.EditorActions.SaveAction;
import com.mxgraph.swing.mxGraphComponent;
import com.mxgraph.swing.util.mxGraphActions;
import com.mxgraph.util.mxEvent;
import com.mxgraph.util.mxEventObject;
import com.mxgraph.util.mxResources;
import com.mxgraph.util.mxEventSource.mxIEventListener;
import com.mxgraph.view.mxGraphView;
import java.awt.Component;
import java.awt.event.ComponentListener;
import java.awt.event.ContainerListener;
import java.awt.event.HierarchyBoundsListener;
import java.awt.event.HierarchyListener;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseListener;
import java.lang.ref.Reference;
import javax.swing.event.AncestorListener;
import vnetlab.manager.Manager;
import vnetlab.manager.StatusListner;
import vnetlab.ui.editor.EditorActions.ExecuteAction;
import vnetlab.ui.editor.EditorActions.PauseAction;
import vnetlab.ui.editor.EditorActions.ResumeAction;
import vnetlab.ui.editor.EditorActions.StopAction;

public class EditorToolBar extends JToolBar implements StatusListner
{

	/**
	 * 
	 */
	private static final long serialVersionUID = -3979320704834605323L;

	/**
	 * 
	 * @param frame
	 * @param orientation
	 */
	private boolean ignoreZoomChange = false;

	/**
	 * 
	 */
	public EditorToolBar(final BasicGraphEditor editor, int orientation)
	{
		super(orientation);
		setBorder(BorderFactory.createCompoundBorder(BorderFactory
				.createEmptyBorder(3, 3, 3, 3), getBorder()));
		setFloatable(false);

		add(editor.bind("New", new NewAction(), "/vnetlab/ui/images/new.gif"));
		add(editor.bind("Open", new OpenAction(), "/vnetlab/ui/images/open.gif"));
		add(editor.bind("Save", new SaveAction(false), "/vnetlab/ui/images/save.gif"));

		addSeparator();

		add(editor.bind("Print", new PrintAction(),"/vnetlab/ui/images/print.gif"));

		addSeparator();

//		add(editor.bind("Cut", TransferHandler.getCutAction(), "/vnetlab/ui/images/cut.gif"));
//		add(editor.bind("Copy", TransferHandler.getCopyAction(),"/vnetlab/ui/images/copy.gif"));
//		add(editor.bind("Paste", TransferHandler.getPasteAction(),"/vnetlab/ui/images/paste.gif"));
//
//		addSeparator();

		add(editor.bind("Delete", mxGraphActions.getDeleteAction(),"/vnetlab/ui/images/delete.gif"));

		addSeparator();
//
//		add(editor.bind("Undo", new HistoryAction(true),"/vnetlab/ui/images/undo.gif"));
//		add(editor.bind("Redo", new HistoryAction(false),"/vnetlab/ui/images/redo.gif"));
//
//		addSeparator();

		final mxGraphView view = editor.getGraphComponent().getGraph().getView();
		final JComboBox zoomCombo = new JComboBox(new Object[] { "400%", "200%", "150%", "100%", "75%", "50%", mxResources.get("page"), mxResources.get("width"), mxResources.get("actualSize") });
		zoomCombo.setEditable(true);
		zoomCombo.setMinimumSize(new Dimension(75, 0));
		//zoomCombo.setPreferredSize(new Dimension(75, 0));
		zoomCombo.setMaximumSize(new Dimension(75, 100));
		zoomCombo.setMaximumRowCount(9);
		add(zoomCombo);

		// Sets the zoom in the zoom combo the current value
		mxIEventListener scaleTracker = new mxIEventListener()
		{
			/**
			 *
			 */
			public void invoke(Object sender, mxEventObject evt)
			{
				ignoreZoomChange = true;

				try
				{
					zoomCombo.setSelectedItem((int) Math.round(100 * view.getScale())+"%");
				}
				finally
				{
					ignoreZoomChange = false;
				}
			}
		};

                //Adiciona os botões de executar e contruir a topologia
                addSeparator();
                JButton executeButton = new JButton(editor.bind("Execute", new ExecuteAction(), "/vnetlab/ui/images/execute.png"));
                JButton stopButton = new JButton(editor.bind("Stop", new StopAction(), "/vnetlab/ui/images/stop.png"));
                JButton pauseButton = new JButton(editor.bind("Pause", new PauseAction(), "/vnetlab/ui/images/pause.png"));
                JButton resumeButton = new JButton(editor.bind("Resume", new ResumeAction(), "/vnetlab/ui/images/resume.png"));
                
                executeButton.setText("EXECUTE");
                stopButton.setText("STOP");
                pauseButton.setText("PAUSE");
                resumeButton.setText("RESUME");
                
                add(executeButton);
                add(stopButton);
                //add(pauseButton);
                //add(resumeButton);
                addSeparator();
               
                refreshToolBar(Status.STOP);
                Manager.getInstance().addStatusListner(this);
                
		// Installs the scale tracker to update the value in the combo box
		// if the zoom is changed from outside the combo box
		view.getGraph().getView().addListener(mxEvent.SCALE, scaleTracker);
		view.getGraph().getView().addListener(mxEvent.SCALE_AND_TRANSLATE, scaleTracker);

		// Invokes once to sync with the actual zoom value
		scaleTracker.invoke(null, null);

		zoomCombo.addActionListener(new ActionListener()
		{
			/**
			 * 
			 */
			public void actionPerformed(ActionEvent e)
			{
				mxGraphComponent graphComponent = editor.getGraphComponent();

				// Zoomcombo is changed when the scale is changed in the diagram
				// but the change is ignored here
				if (!ignoreZoomChange)
				{
					String zoom = zoomCombo.getSelectedItem().toString();

					if (zoom.equals(mxResources.get("page")))
					{
						graphComponent.setPageVisible(true);
						graphComponent
								.setZoomPolicy(mxGraphComponent.ZOOM_POLICY_PAGE);
					}
					else if (zoom.equals(mxResources.get("width")))
					{
						graphComponent.setPageVisible(true);
						graphComponent
								.setZoomPolicy(mxGraphComponent.ZOOM_POLICY_WIDTH);
					}
					else if (zoom.equals(mxResources.get("actualSize")))
					{
						graphComponent.zoomActual();
					}
					else
					{
						try
						{
							zoom = zoom.replace("%", "");
							double scale = Math.min(16, Math.max(0.01,
									Double.parseDouble(zoom) / 100));
							graphComponent.zoomTo(scale, graphComponent
									.isCenterZoom());
						}
						catch (Exception ex)
						{
							JOptionPane.showMessageDialog(editor, ex
									.getMessage());
						}
					}
				}
			}
		});
	}

        public void refreshToolBar(Status status){
            switch(status){
                case STOP:
                    enableAllComponents(true);
//                    enableComponent("EXECUTE", true);
//                    enableComponent("PAUSE", false);
                    enableComponent("STOP", false);
//                    enableComponent("RESUME", false);
                    break;
                case EXECUTE:
                    enableAllComponents(false);
                    //enableComponent("EXECUTE", false);
//                    enableComponent("PAUSE", true);
                    enableComponent("STOP", true);
//                    enableComponent("RESUME", false);
                    break;
//                case PAUSE:
//                    enableComponent("EXECUTE", false);
////                    enableComponent("PAUSE", false);
//                    enableComponent("STOP", true);
////                    enableComponent("RESUME", true);
//                    break;
            }
        }


        public void enableAllComponents(boolean enable){
            for(Component c: getComponents()){
                if(c instanceof JButton){
                    c.setEnabled(enable);
                }
            }
        }
        public void enableComponent(String name, boolean enable){
            for(Component c: getComponents()){
                if(c instanceof JButton){
                    if( ((JButton)c).getText() != null){
                        if(((JButton)c).getText().equalsIgnoreCase(name)){
                            c.setEnabled(enable);
                        }
                    }
                }
            }
        }
        
        public void statusModified(Status status) {
           refreshToolBar(status);
        }
}
